package com.tengju.motivation.application.activity;

import com.tengju.motivation.application.shared.ApplicationException;
import com.tengju.motivation.domain.model.activity.*;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class ActivityApplicationService {

    @Value("${activity.can.edit.in.progress}")
    private boolean canEditInProgress;

    private final ActivityRepository activityRepository;

    public void delete(ActivityId activityId) {
        Activity activity = activityRepository.getActivityById(activityId);
        if (activity == null) {
            throw ApplicationException.error("活动不存在");
        }
        if (activity.isInProgress() && !canEditInProgress) {
            throw ApplicationException.error("活动进行中，不可删除，请联系@孙林");
        }
        activityRepository.delete(activityId);
    }

    @Transactional
    public void save(ActivityId activityId, List<ActivityTarget> targets) {
        Activity activity = activityRepository.getActivityById(activityId);
        if (activity == null) {
            throw ApplicationException.error("活动不存在");
        }
        if (CollectionUtils.isEmpty(targets)) {
            return;
        }
        if (activity.isInProgress() && !canEditInProgress) {
            throw ApplicationException.error("活动进行中，不可修改，请联系@孙林");
        }

        List<ActivityTarget> existTargets = activityRepository.getTargetList(activityId);
        ActivityTargetSet needRemoveTargets = new ActivityTargetSet(activityId, existTargets);

        List<ActivityTarget> newTargets = new ArrayList<>();
        targets.forEach(target -> {
            //值为0的目标不处理
            if (target != null && target.isValid()) {
                needRemoveTargets.remove(target);
                if (target.getTargetId() == null) {
                    newTargets.add(target);
                } else {
                    activityRepository.update(target);
                }
            }
        });
        if (!newTargets.isEmpty()) {
            activityRepository.add(newTargets);
        }
        if (!needRemoveTargets.isEmpty()) {
            activityRepository.remove(needRemoveTargets.getIds());
        }
    }


}
